package com.jiezuo.common.util;

//import sun.misc.BASE64Decoder;
//import sun.misc.BASE64Encoder;

import java.io.*;
import java.util.Base64;
import java.util.Date;

/**
 * @Author: 庞留杰
 * @Date: 2022-06-25 10:18
 * @Description: *
 */
public class Base64Util {


    //base64字符串转化成图片
    public static String decoderFile(String imgStr,String filePath,String fileName) { //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) {
            return null;
        }
        String time = DateTimeUtil.format(new Date(), DateTimeUtil.DATE);
        filePath = filePath + "/" + time;

        File saveFile = new File(filePath);
        //判断文件夹是否存在，不存在创建
        if (!(saveFile.exists() && saveFile.isDirectory())) {
            saveFile.mkdirs();//支持多级文件夹创建
        }
        fileName= System.currentTimeMillis()+fileName;
//        BASE64Decoder decoder = new BASE64Decoder();// 方法过期
        Base64.Decoder decoder=  Base64.getDecoder();
        try {
//            byte[] b = decoder.decodeBuffer(imgStr);
            byte[] b = decoder.decode(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(filePath+"/"+fileName);
            out.write(b);
            out.flush();
            out.close();
            return time+"/"+fileName;
        } catch (Exception e) {
            return null;
        }
    }


    //图片转化成base64字符串
    public static String encoderStr(String imgFile) {//将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
//        BASE64Encoder encoder = new BASE64Encoder(); // 方法过期
//        return encoder.encode(data);//返回Base64编码过的字节数组字符串
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(data);
    }
}
